<script setup lang="ts">
// @ts-ignore
import { ref, reactive, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { authAPI } from '@/http/leancloud';
// @ts-ignore
import { ElMessage } from 'element-plus';
// @ts-ignore
import { Moon, Sunny, Location, User, Lock } from '@element-plus/icons-vue';

// 表单数据
const loginForm = reactive({
  username: '',
  password: '',
  captcha: '',
  rememberMe: false
});

// 表单引用
const loginFormRef = ref();

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
};

// 加载状态
const loading = ref(false);
// 暗黑模式
const isDarkMode = ref(false);

// 验证码图片
const captchaImg = ref('');

// 生成随机验证码图片
const generateCaptcha = () => {
  const randomStr = Math.random().toString(36).substring(2, 8);
  captchaImg.value = randomStr;
};

onMounted(() => {
  generateCaptcha();
});

const router = useRouter();
const route = useRoute();

// 切换暗黑模式
const toggleDarkMode = () => {
  isDarkMode.value = !isDarkMode.value;
  document.documentElement.classList.toggle('dark', isDarkMode.value);
};

// 登录方法
const handleLogin = async () => {
  if (!loginFormRef.value) return;
  
  try {
    // 表单验证
    await loginFormRef.value.validate();
    
    loading.value = true;
    
    // 调用登录API
    const result = await authAPI.login(loginForm.username, loginForm.password);
    
    if (result.success) {
      ElMessage.success('登录成功');
      
      // 如果选择了记住我，则保存用户信息到本地存储
      if (loginForm.rememberMe) {
        localStorage.setItem('currentUser', JSON.stringify(result));
      }
      
      // 获取重定向URL，如果存在则跳转到该URL，否则跳转到首页
      const redirectUrl = route.query.redirect as string || '/';
      router.push(redirectUrl);
    } else {
      ElMessage.error('登录失败，请检查用户名和密码');
      // 刷新验证码
      generateCaptcha();
    }
  } catch (error: any) {
    ElMessage.error(error.message || '登录出错，请稍后再试');
    // 刷新验证码
    generateCaptcha();
  } finally {
    loading.value = false;
  }
};

// 注册弹窗显示状态
const registerDialogVisible = ref(false);
// 注册表单数据
const registerForm = reactive({
  username: '',
  password: ''
});
// 注册表单引用
const registerFormRef = ref();
// 注册表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
};
// 注册按钮 loading
const registerLoading = ref(false);

// 打开注册弹窗
const goToRegister = () => {
  registerDialogVisible.value = true;
};
// 注册方法
const handleRegister = async () => {
  if (!registerFormRef.value) return;
  try {
    await registerFormRef.value.validate();
    registerLoading.value = true;
    // 调用 LeanCloud 注册接口
    const result = await authAPI.register(registerForm.username, registerForm.password);
    if (result.success) {
      ElMessage.success('注册成功，请登录');
      registerDialogVisible.value = false;
      // 清空注册表单
      registerForm.username = '';
      registerForm.password = '';
    } else {
      // 兼容 LeanCloud 错误对象
      let errMsg = '注册失败';
      if (result.error && typeof result.error === 'object') {
        if (result.error.response && result.error.response.data && result.error.response.data.error) {
          errMsg = result.error.response.data.error;
        } else if (result.error.message) {
          errMsg = result.error.message;
        }
      }
      ElMessage.error(errMsg);
    }
    registerLoading.value = false;
  } catch (error: any) {
    registerLoading.value = false;
    ElMessage.error(error.message || '注册出错');
  }
};
</script>

<template>
  <div class="login-container">
    <!-- 左侧城市背景图 -->
    <div class="login-left">
      <div class="logo-area">
        <img src="@/assets/images/logo.svg" class="logo-icon" alt="TMS Logo" />
        <span class="logo-text">TMS运输管理系统</span>
      </div>
    </div>
    
    <!-- 右侧登录表单 -->
    <div class="login-right">
      <!-- 顶部工具栏 -->
      <div class="top-tools">
        <el-button class="icon-button" circle @click="toggleDarkMode">
          <el-icon>
            <Moon v-if="isDarkMode" />
            <Sunny v-else />
          </el-icon>
        </el-button>
        <el-button class="icon-button" circle>
          <el-icon><Location /></el-icon>
        </el-button>
      </div>
      
      <div class="login-form">
        <h1 class="welcome-title">欢迎回来</h1>
        <p class="welcome-subtitle">输入您的账号和密码登录</p>
        
        <el-form 
          ref="loginFormRef"
          :model="loginForm"
          :rules="rules"
          status-icon
          class="login-form-content"
        >
          <el-form-item prop="username">
            <el-input 
              v-model="loginForm.username" 
              placeholder="请输入账号"
              size="large"
            >
              <template #prefix>
                <el-icon><User /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item prop="password">
            <el-input 
              v-model="loginForm.password" 
              type="password" 
              placeholder="请输入密码"
              size="large"
              show-password
            >
              <template #prefix>
                <el-icon><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          
          <el-form-item prop="captcha">
            <div class="captcha-container">
              <el-input 
                v-model="loginForm.captcha" 
                placeholder="请输入验证码"
                size="large"
                class="captcha-input"
              />
              <div class="captcha-image" @click="generateCaptcha">
                <div class="mock-captcha">{{ captchaImg }}</div>
              </div>
            </div>
          </el-form-item>
          
          <div class="form-options">
            <el-checkbox v-model="loginForm.rememberMe">记住密码</el-checkbox>
          </div>
          
          <el-form-item>
            <el-button 
              type="primary" 
              class="login-button" 
              @click="handleLogin" 
              :loading="loading"
              size="large"
            >
              登 录
            </el-button>
          </el-form-item>
          <!-- 新增注册按钮 -->
          <el-form-item>
            <el-button 
              type="default" 
              class="register-button" 
              @click="goToRegister"
              size="large"
              style="width: 100%;"
            >
              注 册
            </el-button>
          </el-form-item>
        </el-form>
        
        <div class="login-agreement">
          登录即视为同意 <el-link type="primary" href="#" class="agreement-link">《用户协议》</el-link> 和 <el-link type="primary" href="#" class="agreement-link">《隐私政策》</el-link>
        </div>
      </div>
    </div>
  </div>
  <!-- 注册弹窗 -->
  <el-dialog v-model="registerDialogVisible" title="注册新账号" width="400px" :close-on-click-modal="false">
    <el-form ref="registerFormRef" :model="registerForm" :rules="registerRules" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="registerForm.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" show-password />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleRegister" :loading="registerLoading" style="width: 100%;">注 册</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<style scoped>
.login-container {
  display: flex;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.login-left {
  flex: 1.2;
  background-image: url('@/assets/images/city-bg.png');
  background-size: cover;
  background-position: center;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.logo-area {
  display: flex;
  align-items: center;
  padding: 20px;
}

.logo-icon {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

.logo-text {
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.login-right {
  flex: 0.8;
  display: flex;
  flex-direction: column;
  padding: 20px 40px;
  position: relative;
  background-color: #fff;
}

.top-tools {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 60px;
}

.icon-button {
  margin-left: 10px;
  color: #606266;
}

.login-form {
  max-width: 400px;
  margin: 0 auto;
  width: 100%;
}

.welcome-title {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin-bottom: 10px;
}

.welcome-subtitle {
  font-size: 16px;
  color: #909399;
  margin-bottom: 40px;
}

.login-form-content {
  margin-bottom: 30px;
}

.captcha-container {
  display: flex;
  align-items: center;
}

.captcha-input {
  flex: 1;
}

.captcha-image {
  width: 120px;
  height: 40px;
  margin-left: 10px;
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;
}

.mock-captcha {
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: 'Courier New', monospace;
  font-size: 20px;
  font-weight: bold;
  color: #333;
  letter-spacing: 2px;
  text-decoration: line-through;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.login-button {
  width: 100%;
  height: 44px;
  font-size: 16px;
  border-radius: 4px;
}

.login-agreement {
  text-align: center;
  font-size: 14px;
  color: #909399;
  margin-top: 20px;
}

.agreement-link {
  font-weight: normal;
}

/* 设置输入框样式 */
:deep(.el-input__wrapper) {
  border-radius: 4px;
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #4066FF inset;
}

/* 设置按钮样式 */
:deep(.el-button--primary) {
  background-color: #4066FF;
  border-color: #4066FF;
}

:deep(.el-button--primary:hover) {
  background-color: #5e7bff;
  border-color: #5e7bff;
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #4066FF;
  border-color: #4066FF;
}

:deep(.el-checkbox__label) {
  color: #606266;
}

:deep(.el-link--primary) {
  color: #4066FF;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .login-left {
    flex: 1;
  }
  
  .login-right {
    flex: 1;
  }
}

@media (max-width: 768px) {
  .login-container {
    flex-direction: column;
  }
  
  .login-left {
    flex: none;
    height: 30vh;
  }
  
  .login-right {
    flex: none;
    height: 70vh;
    overflow-y: auto;
  }
}
</style> 